import { defineStore } from 'pinia'
import { store } from '.'
import { ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import { login as loginApi, userLogout } from '@/api/auth'
import { getUserInfo as getUserInfoApi } from '@/api/system/user'
import Storage from '@/utils/storage'
import { getRouters } from '@/api/system/menu/index'
import router from '@/router'
import type { ILogin } from '@/api/auth/type'
import { getCurrentUserInfoApi } from '@/api/athlete'
import { toViewModelAsync, type AthleteViewModel } from '@/api/athlete/transformer'

export const useUserStore = defineStore('user', () => {
	const userInfoDefault = {
		token: Storage.get('token') || '',
		avatar: '',
		introduction: '',
		name: '',
		roles: [] as string[],
		permissions: [] as string[],
		routes: [], // 存储后端返回的路由
		athlete: null as (AthleteViewModel & { yearId?: string | number }) | null // 运动员信息
	}
	const userInfo = ref({ ...userInfoDefault })

	async function login(data: ILogin) {
		const result = await loginApi(data)

		userInfo.value.token = result.data.access_token
		Storage.set('token', result.data.access_token)
	}

	async function userInfoSimple() {
		const userResult = await getUserInfoApi()
		userInfo.value.roles = userResult.data.roles
		userInfo.value.permissions = userResult.data.permissions
		userInfo.value.avatar = import.meta.env.VITE_API_URL + userResult.data.user.avatar
		userInfo.value.name = userResult.data.user.nickName
		return userResult
	}

	/**
	 * 获取当前用户的运动员信息
	 */
	async function getAthleteInfo() {
		try {
			const response = await getCurrentUserInfoApi()
			if (response.data && response.data.id) {
				// 将 AthleteInfo 转换为 AthleteViewModel
				const athleteViewModel = await toViewModelAsync(response.data)
				// 添加 yearId 信息
				userInfo.value.athlete = {
					...athleteViewModel,
					yearId: response.data.yearId
				}
				console.log('获取运动员信息成功:', userInfo.value.athlete)
			} else {
				userInfo.value.athlete = null
				console.log('用户不是运动员')
			}
		} catch (error) {
			console.warn('获取运动员信息失败:', error)
			userInfo.value.athlete = null
		}
	}

	/**
	 * 设置运动员信息
	 */
	function setAthleteInfo(athlete: (AthleteViewModel & { yearId?: string | number }) | null) {
		userInfo.value.athlete = athlete
	}

	/**
	 * 清除年度确认ID（年度确认完成后调用）
	 */
	function clearYearlyConfirmId() {
		if (userInfo.value.athlete) {
			userInfo.value.athlete.yearId = undefined
		}
	}

	async function getUserInfo() {
		const [userResult, routesResult] = await Promise.all([userInfoSimple(), getRouters()])

		const backendRoutes = routesResult.data || []
		userInfo.value.routes = movePropertiesToMeta(backendRoutes)

		// 获取运动员信息
		await getAthleteInfo()

		/* 初始密码提示 */
		if (userResult.data.isDefaultModifyPwd) {
			ElMessageBox.confirm('您的密码还是初始密码，请修改密码！', '安全提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					router.push({
						path: '/system/user/profile',
						query: { activeTab: 'resetPwd' }
					})
				})
				.catch(() => {})
		}
		/* 过期密码提示 */
		if (!userResult.data.isDefaultModifyPwd && userResult.data.isPasswordExpired) {
			ElMessageBox.confirm('您的密码已过期，请尽快修改密码！', '安全提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				closeOnClickModal: false
			})
				.then(() => {
					router.push({
						path: '/system/user/profile',
						query: { activeTab: 'resetPwd' }
					})
				})
				.catch(() => {})
		}

		return {
			...userInfo.value
		}
	}
	function resetUserInfo() {
		Storage.remove('token')
		userInfo.value = {
			...userInfoDefault,
			token: '',
			athlete: null
		}
	}
	async function logout() {
		await userLogout()
		resetUserInfo()
	}

	function setAvatar(val: string) {
		userInfo.value.avatar = val
	}

	return {
		userInfo,
		login,
		getUserInfo,
		userInfoSimple,
		resetUserInfo,
		logout,
		setAvatar,
		// 运动员信息相关方法
		getAthleteInfo,
		setAthleteInfo,
		clearYearlyConfirmId
	}
})

export function useUserStoreWidthOut() {
	return useUserStore(store)
}

/**
 * 将路由节点中的 alwaysShow 和 hidden 属性移动到 meta 对象中
 * @param {Array|Object} routes 要处理的路由配置，可以是数组或单个对象
 * @returns {Array|Object} 处理后的路由配置
 */
export function movePropertiesToMeta(routes: any): any {
	// 如果是数组，递归处理每个元素
	if (Array.isArray(routes)) {
		return routes.map(route => movePropertiesToMeta(route))
	}

	// 如果是对象，进行处理
	if (typeof routes === 'object' && routes !== null) {
		// 创建新的对象，避免直接修改原对象
		const newRoute = { ...routes }

		// 确保 meta 对象存在
		if (!newRoute.meta) {
			newRoute.meta = {}
		}

		// 移动 hidden 属性
		if ('hidden' in newRoute) {
			newRoute.meta.hidden = newRoute.hidden
			delete newRoute.hidden
		}

		// 移动 alwaysShow 属性
		if ('alwaysShow' in newRoute) {
			newRoute.meta.alwaysShow = newRoute.alwaysShow
			delete newRoute.alwaysShow
		}

		// 递归处理子路由
		if (newRoute.children && Array.isArray(newRoute.children)) {
			newRoute.children = movePropertiesToMeta(newRoute.children)
		}

		return newRoute
	}

	// 如果不是数组也不是对象，直接返回
	return routes
}
